import {
	Injectable,
	NotFoundException,
	BadRequestException,
	Logger,
} from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { Product } from "./entities/product.entity";
import { ProductSpec } from "./entities/product-spec.entity";
import { ProductSku } from "./entities/product-sku.entity";
import { CreateProductDto } from "./dto/create-product.dto";
import { UpdateProductDto } from "./dto/update-product.dto";
import { CreateProductSpecDto } from "./dto/create-product-spec.dto";
import { CreateProductSkuDto } from "./dto/create-product-sku.dto";

@Injectable()
export class ProductService {
	private readonly logger = new Logger(ProductService.name);

	constructor(
		@InjectRepository(Product)
		private productRepository: Repository<Product>,
		@InjectRepository(ProductSpec)
		private productSpecRepository: Repository<ProductSpec>,
		@InjectRepository(ProductSku)
		private productSkuRepository: Repository<ProductSku>
	) {}

	async findAll(query: {
		name?: string;
		category?: string;
		status?: string | number;
		page?: string | number;
		limit?: string | number;
		sort?: string;
		order?: string;
	}): Promise<[Product[], number]> {
		this.logger.debug("查询参数:", query);

		const { name, category, status, sort, order } = query;
		// 参数类型转换和验证
		const page = query.page ? parseInt(String(query.page), 10) : 1;
		const limit = query.limit ? parseInt(String(query.limit), 10) : 10;

		if (isNaN(page) || isNaN(limit) || page < 1 || limit < 1) {
			throw new BadRequestException("分页参数无效");
		}

		const queryBuilder = this.productRepository
			.createQueryBuilder("product")
			.leftJoinAndSelect("product.skus", "skus");

		// 条件过滤
		if (name) {
			queryBuilder.andWhere("product.name LIKE :name", { name: `%${name}%` });
		}

		if (category) {
			queryBuilder.andWhere("product.category = :category", { category });
		}

		if (status) {
			queryBuilder.andWhere("product.status = :status", {
				status,
			});
		}

		// 分页
		queryBuilder.skip((page - 1) * limit);
		queryBuilder.take(limit);

		// 排序
		if (sort && (sort === "price" || sort === "createdAt")) {
			const direction = order === "asc" ? "ASC" : "DESC";
			queryBuilder.orderBy(`product.${sort}`, direction);
		} else {
			queryBuilder.orderBy("product.id", "DESC");
		}

		try {
			const [products, total] = await queryBuilder.getManyAndCount();

			// 计算每个商品的库存
			products.forEach((product) => product.calculateStock());

			this.logger.debug("查询结果:", { count: total });
			return [products, total];
		} catch (error) {
			this.logger.error("查询失败:", error);
			throw error;
		}
	}

	async findOne(id: number): Promise<Product> {
		if (!id || isNaN(id)) {
			throw new BadRequestException("商品ID不能为空且必须为数字");
		}

		const product = await this.productRepository.findOne({
			where: { id },
			relations: ["specs", "skus"],
		});

		if (!product) {
			throw new NotFoundException(`商品ID为${id}的商品不存在`);
		}

		// 计算库存
		product.calculateStock();

		return product;
	}

	async create(createProductDto: CreateProductDto): Promise<Product> {
		const product = this.productRepository.create(createProductDto);
		// 创建新商品时不再需要设置库存字段，因为它们现在是计算属性
		return this.productRepository.save(product);
	}

	async update(
		id: number,
		updateProductDto: UpdateProductDto
	): Promise<Product> {
		const product = await this.findOne(id);
		// 从updateProductDto中移除stock和availableStock字段，因为它们现在是计算属性
		const { stock, availableStock, ...productDataToUpdate } =
			updateProductDto as any;
		Object.assign(product, productDataToUpdate);
		return this.productRepository.save(product);
	}

	async remove(id: number): Promise<void> {
		const product = await this.findOne(id);
		await this.productRepository.remove(product);
	}

	// 规格相关方法
	async createSpec(
		createProductSpecDto: CreateProductSpecDto
	): Promise<ProductSpec> {
		// 检查商品是否存在
		const product = await this.findOne(createProductSpecDto.productId);

		const spec = this.productSpecRepository.create({
			...createProductSpecDto,
			product,
			productId: createProductSpecDto.productId,
		});
		return this.productSpecRepository.save(spec);
	}

	async getProductSpecs(productId: number): Promise<ProductSpec[]> {
		return this.productSpecRepository.find({
			where: { productId },
			order: { id: "ASC" },
		});
	}

	async deleteSpec(id: number): Promise<void> {
		const spec = await this.productSpecRepository.findOne({
			where: { id },
			relations: ["skus"],
		});

		if (!spec) {
			throw new NotFoundException(`规格ID为${id}的规格不存在`);
		}

		// 查找所有与该规格关联的SKU
		console.log(`正在查找规格ID ${id} 关联的SKU...`);
		const relatedSkus = await this.productSkuRepository.find({
			where: { specId: id },
		});

		if (relatedSkus.length > 0) {
			console.log(`找到 ${relatedSkus.length} 个关联的SKU，正在删除...`);
			// 获取SKU ID列表，用于日志记录
			const skuIds = relatedSkus.map((sku) => sku.id);

			// 删除所有关联的SKU
			await this.productSkuRepository.remove(relatedSkus);

			console.log(`已删除规格ID ${id} 关联的所有SKU: ${skuIds.join(", ")}`);
		} else {
			console.log(`规格ID ${id} 没有关联的SKU`);
		}

		// 删除规格
		await this.productSpecRepository.remove(spec);
		console.log(`成功删除规格ID ${id}`);
	}

	// SKU相关方法
	async createSku(
		createProductSkuDto: CreateProductSkuDto
	): Promise<ProductSku> {
		// 检查商品是否存在
		const product = await this.findOne(createProductSkuDto.productId);

		// 查找与该商品关联的规格
		let specId = createProductSkuDto.specId;

		// 如果没有提供specId但有specs数据，尝试找到对应的规格
		if (!specId && Object.keys(createProductSkuDto.specs).length > 0) {
			// 获取规格名称（例如"颜色"或"尺寸"）
			const specName = Object.keys(createProductSkuDto.specs)[0];

			// 查找匹配该名称的规格
			const matchingSpec = await this.productSpecRepository.findOne({
				where: {
					productId: createProductSkuDto.productId,
					name: specName,
				},
			});

			if (matchingSpec) {
				specId = matchingSpec.id;
				console.log(`为SKU自动匹配到规格ID: ${specId} (${specName})`);
			}
		}

		const sku = this.productSkuRepository.create({
			...createProductSkuDto,
			availableStock: createProductSkuDto.stock, // 初始化可用库存等于实际库存
			specId: specId, // 设置规格ID
			product,
			productId: createProductSkuDto.productId,
		});

		// 保存SKU
		const savedSku = await this.productSkuRepository.save(sku);

		return savedSku;
	}

	async getProductSkus(productId: number): Promise<ProductSku[]> {
		return this.productSkuRepository.find({
			where: { productId },
			order: { id: "ASC" },
		});
	}

	async getSku(id: number): Promise<ProductSku> {
		const sku = await this.productSkuRepository.findOne({
			where: { id },
			relations: ["product"],
		});

		if (!sku) {
			throw new NotFoundException(`SKU ID为${id}的SKU不存在`);
		}

		return sku;
	}

	async updateSku(id: number, updateData: any): Promise<ProductSku> {
		const sku = await this.getSku(id);

		// 使用解构更新SKU数据
		Object.assign(sku, updateData);

		// 如果更新了库存，同时更新可用库存
		if (
			updateData.stock !== undefined &&
			updateData.availableStock === undefined
		) {
			sku.availableStock = updateData.stock;
		}

		return this.productSkuRepository.save(sku);
	}

	async updateSkuStock(id: number, quantity: number): Promise<ProductSku> {
		const sku = await this.getSku(id);
		sku.stock += quantity;
		return this.productSkuRepository.save(sku);
	}

	async updateSkuAvailableStock(
		id: number,
		quantity: number
	): Promise<ProductSku> {
		const sku = await this.getSku(id);
		sku.availableStock += quantity;
		return this.productSkuRepository.save(sku);
	}

	async deleteSku(id: number): Promise<void> {
		const sku = await this.getSku(id);
		await this.productSkuRepository.remove(sku);
	}

	// 图片处理相关代码
	// 在保存产品前处理图片数据
	async processProductImage(imageData: string): Promise<string> {
		// 如果是Blob URL，则需要转换
		if (imageData && imageData.startsWith("blob:")) {
			try {
				// 获取Blob内容并转为Base64
				const response = await fetch(imageData);
				const blob = await response.blob();
				return await this.blobToBase64(blob);
			} catch (error) {
				console.error("处理图片失败:", error);
				return "";
			}
		}

		// 如果不是Blob URL或已经是Base64，则直接返回
		return imageData;
	}

	// Blob转Base64工具方法
	private blobToBase64(blob: Blob): Promise<string> {
		return new Promise((resolve, reject) => {
			const reader = new FileReader();
			reader.onloadend = () => resolve(reader.result as string);
			reader.onerror = reject;
			reader.readAsDataURL(blob);
		});
	}

	// 修复现有商品规格的product_id字段
	async fixProductSpecs(): Promise<void> {
		// 获取所有商品规格
		const specs = await this.productSpecRepository.find();

		// 逐个检查并更新规格
		for (const spec of specs) {
			if (!spec.productId) {
				// 查找该规格对应的商品ID
				const product = await this.productRepository
					.createQueryBuilder("product")
					.leftJoinAndSelect("product.specs", "specs")
					.where("specs.id = :specId", { specId: spec.id })
					.getOne();

				if (product) {
					// 更新规格的product_id字段
					spec.productId = product.id;
					await this.productSpecRepository.save(spec);
					console.log(`已修复规格ID ${spec.id} 的product_id为 ${product.id}`);
				} else {
					console.warn(`无法找到规格ID ${spec.id} 对应的商品`);
				}
			}
		}

		console.log("规格数据修复完成");
	}
}
